package tianrun.ziguan.api.calculate.config.service.sync.handler.template;

import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import tianrun.ziguan.api.calculate.config.entity.TUsageAnalysisModule;
import tianrun.ziguan.api.calculate.config.enums.MoldEnum;
import tianrun.ziguan.api.calculate.config.service.sync.SyncType;
import tianrun.ziguan.api.calculate.config.service.sync.handler.AbstractSyncHandler;
import tianrun.ziguan.api.calculate.config.service.sync.handler.SyncHandler;
import tianrun.ziguan.api.calculate.config.service.template.analysis.ITUsageAnalysisModuleService;
import tianrun.ziguan.api.calculate.config.utils.MyBeanUtil;
import tianrun.ziguan.api.calculate.config.utils.Setter;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UsageAnalysisModuleHandler extends AbstractSyncHandler {

    private final ITUsageAnalysisModuleService usageAnalysisModuleService;

    public UsageAnalysisModuleHandler(ITUsageAnalysisModuleService usageAnalysisModuleService) {
        this.usageAnalysisModuleService = usageAnalysisModuleService;
    }

    @Override
    public MoldEnum mold() {
        return MoldEnum.UsageAnalysis;
    }

    @Override
    public SyncType type() {
        return SyncType.TEMPLATE;
    }

    @Override
    public void handler(Set<Long> moduleIds, Set<Long> parentIds) {
        Collection<TUsageAnalysisModule> sources = usageAnalysisModuleService.listByIds(moduleIds);
        Collection<TUsageAnalysisModule> targets = usageAnalysisModuleService.listByTemplateIds(parentIds);
        Map<Long, Map<String, TUsageAnalysisModule>> templateTarget = targets.stream().filter(v -> Objects.nonNull(v.getCalLabel())).collect(Collectors.groupingBy(TUsageAnalysisModule::getTemplateId, Collectors.toMap(TUsageAnalysisModule::getCalLabel, Function.identity())));
        List<TUsageAnalysisModule> list = Lists.newArrayList();
        for (TUsageAnalysisModule source : sources) {
            String key = source.getCalLabel();
            for (Long parentId : parentIds) {
                TUsageAnalysisModule target = new TUsageAnalysisModule();
                Map<String, TUsageAnalysisModule> _targets = templateTarget.getOrDefault(parentId, Collections.emptyMap());
                TUsageAnalysisModule _target = _targets.getOrDefault(key, target);
                list.add(MyBeanUtil.doCopy(source, _target, new Setter<>(_target::setId, _target.getId()), new Setter<>(_target::setTemplateId, parentId)));
            }
        }
        usageAnalysisModuleService.saveOrUpdateBatch(list);
    }
}
